<template>
  <!-- <s-layout title="成长" tabbar="/pages/index/growup" navbar="custom" :bgStyle="template.page"
    :navbarStyle="template.navigationBar" onShareAppMessage> -->
  <s-layout title="成长" class="set-userinfo-wrap" :bgStyle="{ color: '#fff' }">
    <view class="stu-info ss-flex ss-row-between">
      <view class="ss-flex">
        <image class="avatar-img"
          :src="studentInfo.avatar ? sheep.$url.cdn(studentInfo.avatar) : sheep.$url.cdn('https://txz-1332973494.cos.ap-guangzhou.myqcloud.com/static/img/shop/txz.jpg')"
          mode="aspectFill" @click="sheep.$router.go('/pages/student/add?id='+studentInfo.id)">
        </image>
        <view v-if="studentInfo.name">
          <view class="name">{{studentInfo.name}}</view>
          <view class="time">{{studentInfo.age}}岁</view>
        </view>
      </view>
      <!-- <view class="btn" v-if="studentData.length" @click="showSelStu = !showSelStu">切换</view> -->
      <!-- <view class="btn" v-else @click="sheep.$router.go(`/pages/student/add`)">添加学员</view> -->
    </view>
    <view class="box">
      <view class="mask" v-show="showSelStu" @click="showSelStu = !showSelStu"></view>
      <view class="stu-list" v-show="showSelStu">
        <view class="stu-item" v-for="item in studentData" :key="item.studentId" @click="selStu(item)">{{item.name}}
        </view>
      </view>
      <view class="ss-flex stu-detail ss-row-between">
        <!-- <view class="tizhong" @click="sheep.$router.go(`/pages/growup/sgtzIndex`)"> -->
        <view class="tizhong">
          <view class="num">{{preInfo.weight || 0}}千克</view>
          <view class="txt">体重分析</view>
        </view>
        <!-- <view class="shengao" @click="sheep.$router.go(`/pages/growup/sgtzIndex`)"> -->
        <view class="shengao">
          <view class="num">{{preInfo.height || 0}}厘米</view>
          <view class="txt">身高分析</view>
        </view>
        <!-- <view class="shili" @click="sheep.$router.go(`/pages/growup/slIndex`)"> -->
        <view class="shili">
          <view class="num">{{preInfo.leftEye || 0.0}}/{{preInfo.rightEye || 0.0}}</view>
          <view class="txt">视力分析</view>
        </view>
      </view>
      <view class="item-card">
        <view class="tab-list ss-flex ss-p-y-20 ss-p-x-20 ss-row-center" style="padding-bottom: 0;">
          <view class="tab-item" :class="{act: sendData.type == ''}" @click="selTab('')">全部</view>
          <view class="tab-item" :class="{act: sendData.type == 1}" @click="selTab(1)">家长</view>
          <view class="tab-item" :class="{act: sendData.type == 2}" @click="selTab(2)">主理人</view>
          <view class="tab-item" :class="{act: sendData.type == 3}" @click="selTab(3)">陪伴师</view>
        </view>
        <view class="tab-detail">
          <template v-if="accompanyList && accompanyList.length">
            <l-friend-circle :index="index" :objData="item" v-for="(item,index) in accompanyList" :key="index"
              @dianzan="dianzan" @toComment="toComment" @longPressCont="longPressCont"></l-friend-circle>
            <uni-load-more :status="loadStatus" />
          </template>
          <s-empty v-else-if="accompanyList.length === 0 && noData" text="陪伴空空如也~" />
        </view>
      </view>
    </view>
  </s-layout>
  <view class="pl-box" v-if="showComment">
    <uni-forms>
      <uni-forms-item style="padding: 0;">
        <uni-easyinput type="text" :inputBorder="false" class="uni-easyinput" focus confirmType="send" trim="both"
          v-model="plData.content" placeholder="发表评论:" @confirm="sendPl" @blur="handleBlur" />
      </uni-forms-item>
    </uni-forms>
  </view>

  <view class="add-box" v-if="showAdd" @click="toAdd">
    <uni-icons type="plusempty" size="32" color="#fff"></uni-icons>
  </view>
</template>

<script setup>
  import {
    onLoad,
    onShow,
    onHide,
    onReachBottom,
    onPullDownRefresh
  } from '@dcloudio/uni-app';
  import {
    computed,
    ref,
    reactive,
    watch
  } from 'vue';
  import {
    showAuthModal
  } from '@/sheep/hooks/useModal';

  import sheep from '@/sheep';
  import AccompanyApi from '@/sheep/api/member/accompany';
  import StudentApi from '@/sheep/api/member/student';
  import request from '@/sheep/request';
  // 隐藏原生tabBar
  uni.hideTabBar();

  const template = computed(() => sheep.$store('app').template.home);
  const userInfo = computed(() => sheep.$store('user').userInfo);
  const isLogin = computed(() => sheep.$store('user').isLogin);
  // 监听 isLogin 的变化
  watch(isLogin, (newVal, oldVal) => {
    if (newVal) {
      // console.log('用户已登录');
      loadPage()
      getStudentList()
      showAdd.value = true
    } else {
      // console.log('用户已退出登录');
      showAdd.value = false
    }
  })
  let noData = ref(false)
  let accompanyList = reactive([])
  let listPl = reactive([])
  let loadStatus = ref('more')
  let showComment = ref(false)
  let showAdd = ref(false)
  let preInfo = reactive({})
  let plData = reactive({
    recordId: '', //||点评记录编号|query|false|string||
    content: '', //||评论内容|query|false|string||
    type: 1, //||类型 1评论；2回复|query|false|string||
    replyId: '', //||回复评论编号(评论表编号)|query|false|string||
    replyerId: '' //||回复评论人编号|query|false|string||
  })
  let reviewObj = reactive({
    reviewerId: '',
    reviewerName: ''
  })

  let sendData = reactive({
    model: 2, // 1 陪伴，2 成长
    pageSize: 10,
    pageNo: 1,
    publishId: '', // 发布人编号
    type: '', // 发布人类型 1家长；2主理人；3陪伴师
    studentId: '' // 学员编号
  })
  let studentId = ref('')
  let showSelStu = ref(false)
  let studentData = reactive([])
  let studentInfo = reactive({
    name: '',
    age: '',
    id: '',
    avatar: ''
  })
  // 获取列表
  const loadPage = async () => {
    const res = await AccompanyApi.getAccompanyList(sendData);
    if (res.code === 0) {
      uni.showLoading()
      if (sendData.pageNo === 1) {
        accompanyList.splice(0, accompanyList.length); // 清空数组
      }
      if (res.data.list.length) {
        // 使用 Promise.all 来处理所有异步操作
        const processedList = await Promise.all(
          res.data.list.map(async (item) => {
            item.filePath = JSON.parse(item.filePath);
            if (item.filePath?.type === 1 && item.filePath?.path.length == 1) {
              // const imageInfo = await getImageSize(item.filePath.path[0]);
              // if (imageInfo) {
              //   const scaledImage = getScaledDimensions(imageInfo.width, imageInfo.height, 400,
              //     300); // 最大宽度400rpx，最大高度300rpx
              //   item.imageWidth = scaledImage.width;
              //   item.imageHeight = scaledImage.height;
              // }
              item.imageWidth = 160;
              item.imageHeight = 160;
            }
            // // #ifndef MP-WEIXIN
            // if (item.filePath?.type === 2) {
            //   const videoInfo = await getVideoSize(item.filePath.path[0]);
            //   if (videoInfo) {
            //     const scaledVideo = getScaledDimensions(videoInfo.width, videoInfo.height, 400,
            //       300); // 最大宽度400rpx，最大高度300rpx
            //     item.videoWidth = scaledVideo.width;
            //     item.videoHeight = scaledVideo.height;
            //   }
            // }
            // // #endif

            item.createTimeText = formatTimeAgo(item.createTime);
            return item; // 返回处理后的 item
          })
        );

        // 用处理过的 list 更新 accompanyList
        accompanyList.push(...processedList);
      }
      uni.hideLoading()

      // 根据数据总量更新 loadStatus
      if (accompanyList.length >= res.data.total) {
        loadStatus.value = 'noMore';
      } else {
        loadStatus.value = 'more';
      }
      noData.value = true
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg,
      });
    }
  }
  // 获取学生列表
  const getStudentList = async () => {
    const res = await StudentApi.getStudentPage({
      pageSize: 99,
      pageNo: 1
    })
    if (res.code == 0) {
      studentData.splice(0, studentData.length)
      let student = null
      if (res.data.list.length && !studentId.value) {
        // studentInfo.name = res.data.list[0].name
        // studentInfo.age = res.data.list[0].age
        // studentInfo.id = res.data.list[0].id
        // studentInfo.avatar = res.data.list[0].avatar
        // sendData.studentId = res.data.list[0].id
        student = res.data.list[0]
        getStuDetail(res.data.list[0].id)
      } else if (res.data.list.length && studentId.value) {
        student = res.data.list.find(item => {
          return item.id == studentId.value
        })
      }
      studentInfo.name = student.name
      studentInfo.age = student.age
      studentInfo.id = student.id
      studentInfo.avatar = student.avatar
      sendData.studentId = student.id
      studentData.push(...res.data.list)
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg,
      })
    }
  }
  const formatNumber = (val) => {
    // 判断是否为整数
    if (Number.isInteger(val)) {
      return val + ".0" // 如果是整数，添加 ".0"
    }
    return val // 如果有小数点，保持原样
  }
  // 获取上一个记录的身高体重视力
  const getStuDetail = async (studentId) => {
    const res = await AccompanyApi.getGrowthRecord({
      studentId
    })
    if (res.code == 0) {
      res.data.leftEye = res.data.leftEye ? formatNumber(res.data.leftEye) : res.data.leftEye
      res.data.rightEye = res.data.rightEye ? formatNumber(res.data.rightEye) : res.data.rightEye
      Object.assign(preInfo, res.data);
    } else {
      uni.showToast({
        icon: 'none',
        title: res.msg,
      })
    }
  }
  // 选择学生
  const selStu = (item) => {
    showSelStu.value = false
    studentInfo.name = item.name
    studentInfo.age = item.age
    studentInfo.id = item.id
    studentInfo.avatar = item.avatar
    sendData.studentId = item.id
    sendData.pageNo = 1
    accompanyList.length = 0
    noData.value = false
    getStuDetail(sendData.studentId)
    loadPage()
  }
  onLoad(async (options) => {
    if (!isLogin.value) {
      studentInfo.name = ""
      studentInfo.age = ""
      studentInfo.id = ""
      studentInfo.avatar = ""
      preInfo.weight = ''
      preInfo.height = ''
      preInfo.leftEye = ''
      preInfo.rightEye = ''
      accompanyList.splice(0, accompanyList.length)
      showAuthModal()
      return
    }
    showAdd.value = true
    studentId.value = options.id
    await getStudentList()
    loadPage()
  })
  onHide(() => {
    uni.$off('stuId')
  })

  // 详情TAB
  const selTab = (index) => {
    sendData.type = index
    sendData.pageNo = 1
    accompanyList.length = 0
    noData.value = false
    loadPage()
  }
  // 长按删除内容
  const longPressCont = (id) => {
    uni.showActionSheet({
      itemList: ['删除'],
      success: (res) => {
        if (res.tapIndex == 0) {
          AccompanyApi.deleteContent(id).then(res => {
            if (res.code == 0) {
              const index = accompanyList.findIndex(item => item.id == id.id)
              if (index != -1) {
                accompanyList.splice(index, 1)
              }
              uni.showToast({
                icon: 'none',
                title: '删除成功',
              })
            } else {
              uni.showToast({
                icon: 'none',
                title: res.msg,
              })
            }
          })
        }
      }
    })
  }
  // 点赞
  const dianzan = (obj) => {
    if (obj.isLike == 1) {
      AccompanyApi.deleteLike({ // 取消点赞
        id: obj.id
      }).then(res => {
        if (res.code == 0) {
          const targetItem = accompanyList.find(item => item.id === obj.id)
          if (targetItem) {
            targetItem.isLike = 0
            targetItem.likedList = targetItem.likedList.filter(user => user !== userInfo.value.nickname)
          }
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg,
          })
        }
      })
    } else {
      AccompanyApi.addLike({ // 点赞
        recordId: obj.id
      }).then(res => {
        if (res.code == 0) {
          const targetItem = accompanyList.find(item => item.id === obj.id)
          if (targetItem) {
            targetItem.isLike = 1
            targetItem.likedList.push(userInfo.value.nickname)
          }
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg,
          })
        }
      })
    }
  }
  // 请求图片信息
  const getImageSize = async (url) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: url + "?imageInfo",
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败，状态码：${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(new Error("网络请求失败：" + err.errMsg));
        },
      });
    });
  };
  // 获取视频尺寸的函数
  const getVideoSize = (url) => {
    return new Promise((resolve, reject) => {
      const videoElement = document.createElement('video');
      videoElement.preload = 'metadata'; // 只加载元数据
      videoElement.onloadedmetadata = () => {
        resolve({
          width: videoElement.videoWidth,
          height: videoElement.videoHeight,
        });
      };
      videoElement.onerror = reject;
      videoElement.src = url;
    });
  };
  const getScaledDimensions = (originalWidth, originalHeight, maxWidth, maxHeight) => {
    const widthRatio = maxWidth / originalWidth;
    const heightRatio = maxHeight / originalHeight;
    const scaleFactor = Math.min(widthRatio, heightRatio, 1); // 确保图片不会被放大
    return {
      width: Math.round(originalWidth * scaleFactor),
      height: Math.round(originalHeight * scaleFactor),
    };
  };
  // 添加朋友圈
  const toAdd = () => {
    sheep.$router.go(`/pages/growup/add?id=${studentInfo.id}`)
  }

  // 点击评论
  const toComment = (obj) => {
    if (userInfo.value?.id == obj.reviewObj?.reviewerId) { // 是自己的评论可以删除
      uni.showActionSheet({
        itemList: ['删除'],
        success: (res) => {
          if (res.tapIndex == 0) {
            AccompanyApi.delComment({
              id: obj.reviewObj.id
            }).then(res => {
              if (res.code == 0) {
                const targetItem = accompanyList.find(item => item.id === obj.recordId)
                if (targetItem) {
                  targetItem.reviewList = targetItem.reviewList.filter(user => user.id != obj.reviewObj.id)
                }
                uni.showToast({
                  icon: 'none',
                  title: '删除成功',
                })
              } else {
                uni.showToast({
                  icon: 'none',
                  title: res.msg,
                })
              }
            })
          }
        }
      })
      return
    }
    reviewObj.reviewerId = obj.reviewObj?.reviewerId
    reviewObj.reviewerName = obj.reviewObj?.reviewerName

    plData.type = obj.type
    plData.recordId = obj.recordId
    plData.replyId = obj.reviewObj?.id || ''
    plData.replyerId = obj.reviewObj?.reviewerId || ''
    showComment.value = true
    showAdd.value = false
  }
  // 失去焦点
  const handleBlur = () => {
    showComment.value = false
    showAdd.value = true
  }
  // 评论
  const sendPl = () => {
    showComment.value = false
    showAdd.value = true
    AccompanyApi.addComment(plData).then(res => {

      if (res.code == 0) {
        const targetItem = accompanyList.find(item => item.id === plData.recordId)
        if (targetItem) {
          let obj = {
            content: plData.content,
            replyerId: reviewObj.reviewerId || '',
            replyerName: reviewObj.reviewerName || '',
            reviewerId: userInfo.value?.id,
            reviewerName: userInfo.value?.nickname,
            type: plData.type
          }
          targetItem.reviewList.push(obj)
          reviewObj.reviewerId = ''
          reviewObj.reviewerName = ''
        }
      } else {
        uni.showToast({
          icon: 'none',
          title: res.msg,
        })
      }
      plData.type = 1
      plData.recordId = ''
      plData.replyId = ''
      plData.replyerId = ''
      plData.content = ''
    })
  }
  // 改变时间现实方式
  const formatTimeAgo = (timestamp) => {
    const now = Date.now(); // 当前时间戳
    const diff = now - timestamp; // 时间差（毫秒）
    // 将时间差转换为秒、分钟、小时、天
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (seconds < 60) {
      return `${seconds}秒前`;
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else {
      return `${days}天前`;
    }
  }
  onReachBottom(() => {
    if (loadStatus.value != 'more') return
    loadStatus.value = 'loading'
    sendData.pageNo++
    loadPage()
  })
  onPullDownRefresh(() => {
    sendData.pageNo = 1
    sendData.type = ''
    sendData.studentId = studentData[0].id
    studentInfo.name = studentData[0].name
    studentInfo.age = studentData[0].age
    studentInfo.id = studentData[0].id
    studentInfo.avatar = studentData[0].avatar
    loadPage()
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 800);
  })
</script>

<style scoped lang="scss">
  .add-box {
    position: fixed;
    z-index: 9;
    right: 50rpx;
    bottom: 180rpx;
    border-radius: 50%;
    width: 100rpx;
    height: 100rpx;
    line-height: 100rpx;
    background: #FF6000;
    text-align: center;
  }

  .stu-info {
    margin: 24rpx 24rpx 0;
    border: 2px solid #e6e6e6;
    border-radius: 18rpx 18rpx 0 0;
    padding: 24rpx;

    .avatar-img {
      width: 110rpx;
      height: 110rpx;
      border-radius: 50%;
      margin-right: 24rpx;
    }

    .name {
      font-weight: bold;
      font-size: 30rpx;
    }

    .time {
      color: #999;
      font-size: 26rpx;
    }

    .btn {
      border: 1px solid #e6e6e6;
      border-radius: 16rpx;
      padding: 8rpx 48rpx;
    }
  }

  .box {
    position: relative;

    .mask {
      position: absolute;
      height: 100vh;
      width: 100%;
      background-color: #000;
      opacity: .5;
      z-index: 10;
      left: 0;
      top: 0;
    }

    .stu-list {
      position: absolute;
      z-index: 11;
      right: 48rpx;
      top: -48rpx;
      background: #fff;
      border: 1px solid #e6e6e6;
      border-radius: 8rpx;
      border-bottom: none;

      .stu-item {
        border-bottom: 1px solid #e6e6e6;
        padding: 12rpx 24rpx;
      }
    }

    .stu-detail {
      padding: 24rpx 24rpx 0;

      >view {
        box-sizing: border-box;
        width: 210rpx;
        height: 118rpx;
        border-radius: 16rpx;
        padding: 8rpx;
        text-align: left;

        &.tizhong {
          background: url('../../static/images/tizhong.png') no-repeat 100%/100%;
        }

        &.shengao {
          background: url('../../static/images/shengao.png') no-repeat 100%/100%;
        }

        &.shili {
          background: url('../../static/images/shili.png') no-repeat 100%/100%;
        }

        .num {
          font-weight: bold;
          font-size: 26rpx;
          height: 55rpx;
          line-height: 55rpx;
          padding-left: 70rpx;
        }

        .txt {
          color: #333;
          font-size: 24rpx;
          height: 55rpx;
          padding-left: 20rpx;
          // text-align: center;
        }
      }
    }
  }

  .pl-box {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 100;
    width: 100vw;
    background: #F7F6F7;
    padding: 16rpx;
    box-sizing: border-box
  }

  .uni-easyinput {
    box-sizing: border-box;
    background: #fff;
    padding: 0 12rpx;
    border: none;
    border-radius: 10rpx;
  }

  .uni-easyinput__content.is-input-border {
    border: none;
  }

  .item-card {
    background: #fff;

    .tab-list {
      border-bottom: 1px solid #eee;

      .tab-item {
        // @include text-line(1);
        white-space: nowrap;
        flex: 1;
        text-align: center;
        line-height: 48rpx;
        font-size: 30rpx;
        font-weight: bold;
        padding: 0 0 10rpx;

        &.act {
          color: #FF6000;
          position: relative;
          font-weight: bold;

          &:after {
            height: 4rpx;
            width: 48rpx;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            content: " ";
            background-color: #FF6000;
            bottom: 10rpx;
          }
        }
      }
    }

    .tab-detail {
      position: relative;

      .mask {
        position: absolute;
        height: 100vh;
        width: 100%;
        background-color: #000;
        opacity: .5;
        z-index: 10;
        left: 0;
        top: 0;
      }

      .stu-list {
        position: absolute;
        z-index: 11;
        right: 4rpx;
        top: 0rpx;
        background: #fff;
        border: 1px solid #e6e6e6;
        border-radius: 8rpx;
        border-bottom: none;

        .stu-item {
          border-bottom: 1px solid #e6e6e6;
          padding: 12rpx 24rpx;
        }
      }
    }
  }
</style>